package com.zzlzd.drp.util;



import com.zzlzd.drp.config.RedisUtils;
import com.zzlzd.drp.domain.UserDto;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Map;

public class TokenUtils {
    private final RedisUtils redisUtils;

    public TokenUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    /**
     * 生成token放入redisRedisConfig.java
     */
    public String  createToken(UserDto user){
        try {
            String token = TokenProccessor.getInstance().makeToken();
            String old = user.getToken();
            if(old!=null){
                if(redisUtils.hasKey(old)){
                    redisUtils.del(old);
                }
            }
            ArrayList<Map<String, Object>> dataStr = new ArrayList<>();
            user.setToken(token);
            dataStr.add(user.getMap());
            redisUtils.set(token,dataStr);//新增
            if(redisUtils.hasKey(token)){
                return token;
            }else {
                return null;
            }
        }catch (Exception e){
            System.out.println("登录删除旧token出错");
            return null;
        }
    }
    /**
     * 移除token
     */
    public void removeToken(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            redisUtils.del(token);
        }catch (Exception e){
            System.out.println("移出token："+e);
        }
    }

    /**
     * 判断请求参数中的token是否和session中一致
     * @param request
     * @return
     */
    public boolean TokenIs(HttpServletRequest request){
        String token = request.getHeader("token");
        return redisUtils.hasKey(token);
    }

    /***
     * 是否在线
     * @param token
     * @return
     */
    public boolean TokenOnle(String token){
        return redisUtils.hasKey(token);
    }
}
